layui.use(['table', 'form'], function () {
    var laydate = layui.laydate;
    var table = layui.table;
    var form = layui.form;
    laydate.render({
        elem: '#datetime',
        type: 'datetime',
        fullPanel: true // 2.8+
    });

    // 在Ajax请求成功后，将查询结果添加到下拉列表中的选项中
    $.ajax({
        url: '../../SearchGroupList',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            // 动态添加新的选项
            $.each(data, function(index, item) {
                var option = $('<option></option>').val(item.id).text(item.name);
                $('#group').append(option);
            });
            // 相关操作
            form.render(); // 渲染全部表单
        },
        error: function(xhr, textStatus, errorThrown) {
            alert('获取数据失败');
        }
    });

    form.verify({
        peopleLimit: function(value, item) {
            if (!/^\d+$/.test(value)) {
                return '人数限制必须为整数';
            }
        }
    });

    form.on('submit(updateForm-submit)', function (data) {
        $.ajax({
            url: '../../UpdateCompetitionInformation',
            data: {
                ci_id: data.field.no,
                venue : data.field.venue,
                nature : data.field.nature,
                peopleLimit : data.field.peopleLimit,
                group : data.field.group,
                project:data.field.project,
                datetime:data.field.datetime,
            },
            method: 'POST',
            dataType: 'json',
            success: function (result) {
                if (result.code === 200) { // 修改成功
                    layer.msg('修改比赛赛程成功');
                    layer.closeAll('page');
                } else if(result.code === 100){
                    layer.msg(result.msg);
                }

                $.ajax({
                    url: '../../SearchCompetitionInformation',
                    method: 'POST',
                    dataType: 'json',
                    success: function (res) {
                        table.reload('schedule-table',{
                            page: {
                                curr: 1 // 重新从第 1 页开始
                            },
                            data: res.data
                        });
                    },
                    error: function (err) {
                        layer.msg( '查询数据时发生错误，请稍后再试！');
                    }
                });
            },
            error: function (err) {
                layer.msg( '查询数据时发生错误，请稍后再试！');
            }
        });
        return false;
    });
})
